import { useState, useEffect } from 'react';
import {
  Table, Button, DatePicker, Select, Card, Badge, Avatar,
  Modal, Statistic,
  Tag, Spin, Skeleton
} from 'antd';
import {
   FilterOutlined, BarChartOutlined,
  
  UserSwitchOutlined, 
} from '@ant-design/icons';
import dayjs from 'dayjs';
import 'dayjs/locale/zh-cn';
import { ArrangeDetails } from '../../component/arrange/ArrangeDetails';
import HistoryStatsModal from '../../component/arrange/HistoryStatsModal';

// 配置dayjs中文显示
dayjs.locale('zh-cn');

// 模拟员工数据
const doctors = [
  {
    id: 'li',
    name: '李员工',
    specialty: '推拿按摩',
    avatar: 'https://picsum.photos/id/91/32/32'
  },
  {
    id: 'chen',
    name: '陈员工',
    specialty: '针灸治疗',
    avatar: 'https://picsum.photos/id/33/32/32'
  },
  {
    id: 'zhao',
    name: '赵员工',
    specialty: '艾灸养生',
    avatar: 'https://picsum.photos/id/64/32/32'
  },
  {
    id: 'wang',
    name: '王员工',
    specialty: '拔罐疗法',
    avatar: 'https://picsum.photos/id/22/32/32'
  },
  {
    id: 'wang2',
    name: '王员工',
    specialty: '拔罐疗法',
    avatar: 'https://picsum.photos/id/22/32/32',
    isOnLeave: true
  }
];

// 模拟排班记录数据
const generateMockScheduleData = () => {
  const statuses = ['normal', 'adjusted', 'canceled', 'replaced'];
  const services = ['推拿按摩', '针灸治疗', '艾灸养生', '拔罐疗法'];

  return Array.from({ length: 50 }, (_, i) => {
    const baseDate = dayjs().subtract(Math.floor(Math.random() * 45), 'day');
    const status = statuses[Math.floor(Math.random() * statuses.length)];

    // 为不同状态设置不同的员工
    let originalDoctor = doctors[Math.floor(Math.random() * doctors.length)];
    let actualDoctor = originalDoctor;

    if (status === 'adjusted' || status === 'replaced') {
      // 随机选择另一位员工
      let newDoctor;
      do {
        newDoctor = doctors[Math.floor(Math.random() * doctors.length)];
      } while (newDoctor.id === originalDoctor.id);
      actualDoctor = newDoctor;
    } else if (status === 'canceled') {
      actualDoctor = null;
    }

    return {
      id: `shift-${i + 1}`,
      date: baseDate.format('YYYY-MM-DD'),
      timeSlot: `${Math.floor(Math.random() * 12) + 8}:00-${Math.floor(Math.random() * 12) + 9}:00`,
      originalDoctor,
      actualDoctor,
      service: services[Math.floor(Math.random() * services.length)],
      reservationCount: Math.floor(Math.random() * 3) + 1,
      maxReservation: 3,
      status,
      operator: i % 5 === 0 ? '系统自动排班' : '管理员（张主任）',
      updateTime: baseDate.add(Math.floor(Math.random() * 24), 'hour').format('YYYY-MM-DD HH:mm')
    };
  }).sort((a, b) => dayjs(b.date).valueOf() - dayjs(a.date).valueOf());
};

// 获取状态标签样式
const getStatusBadge = (status) => {
  switch (status) {
    case 'normal':
      return <Badge status="success" text="正常排班" />;
    case 'adjusted':
      return <Badge status="processing" text="已调班" />;
    case 'canceled':
      return <Badge status="error" text="已取消" />;
    case 'replaced':
      return <Badge status="info" text="代班" />;
    default:
      return <Badge status="default" text="未知状态" />;
  }
};



export const ArrangeHistory = () => {
  const [isShow, setIsShow] = useState(true);
  setTimeout(() => {
    setIsShow(false);
  }, 2000);
  
  // 状态管理
  const [scheduleData, setScheduleData] = useState([]);
  const [filteredData, setFilteredData] = useState([]);
  const [loading, setLoading] = useState(true);
  const [currentPage, setCurrentPage] = useState(1);
  const [pageSize, setPageSize] = useState(5);
  const [totalRecords, setTotalRecords] = useState(0);

  // 筛选条件
  const [dateRange, setDateRange] = useState([
    dayjs().subtract(45, 'day'),
    dayjs()
  ]);
  const [doctorFilter, setDoctorFilter] = useState('');
  const [statusFilter, setStatusFilter] = useState('');

  // 模态框状态
  const [detailModalVisible, setDetailModalVisible] = useState(false);
  const [statsModalVisible, setStatsModalVisible] = useState(false);
  const [selectedSchedule, setSelectedSchedule] = useState(null);
  
  // 详情页标签切换状态（替代TabPane）
  const [activeDetailTab, setActiveDetailTab] = useState('reservations');

  // 统计数据
  const [statistics, setStatistics] = useState({
    totalShifts: 0,
    adjustedShifts: 0,
    cancelledShifts: 0,
    replacedShifts: 0,
    adjustedChange: 0,
    cancelledChange: 0,
    filterDateRange: ''
  });

  // 初始化数据
  useEffect(() => {
    const fetchData = async () => {
      setLoading(true);
      // 模拟API请求延迟
      await new Promise(resolve => setTimeout(resolve, 800));

      const data = generateMockScheduleData();
      setScheduleData(data);
      setFilteredData(data);
      setTotalRecords(data.length);

      // 计算初始统计数据
      calculateStatistics(data);

      setLoading(false);
    };

    fetchData();
  }, []);

  // 当筛选条件变化时重新筛选数据
  useEffect(() => {
    if (scheduleData.length === 0) return;

    let result = [...scheduleData];

    // 日期范围筛选
    if (dateRange[0] && dateRange[1]) {
      const start = dateRange[0].startOf('day').valueOf();
      const end = dateRange[1].endOf('day').valueOf();

      result = result.filter(item => {
        const itemDate = dayjs(item.date).valueOf();
        return itemDate >= start && itemDate <= end;
      });
    }

    // 员工筛选
    if (doctorFilter) {
      result = result.filter(item =>
        item.originalDoctor.id === doctorFilter ||
        (item.actualDoctor && item.actualDoctor.id === doctorFilter)
      );
    }

    // 状态筛选
    if (statusFilter) {
      result = result.filter(item => item.status === statusFilter);
    }

    setFilteredData(result);
    setTotalRecords(result.length);
    setCurrentPage(1);

    // 重新计算统计数据
    calculateStatistics(result);
  }, [dateRange, doctorFilter, statusFilter, scheduleData]);

  // 计算统计数据
  const calculateStatistics = (data) => {
    const total = data.length;
    const adjusted = data.filter(item => item.status === 'adjusted').length;
    const cancelled = data.filter(item => item.status === 'canceled').length;
    const replaced = data.filter(item => item.status === 'replaced').length;

    // 模拟环比数据
    const adjustedChange = Math.floor(Math.random() * 5) * (Math.random() > 0.5 ? 1 : -1);
    const cancelledChange = Math.floor(Math.random() * 3) * (Math.random() > 0.5 ? 1 : -1);

    // 格式化日期范围显示
    let dateRangeText = '筛选时间：';
    if (dateRange[0] && dateRange[1]) {
      dateRangeText += `${dateRange[0].format('YYYY年MM月DD日')} - ${dateRange[1].format('YYYY年MM月DD日')}`;
    } else if (dateRange[0]) {
      dateRangeText += `${dateRange[0].format('YYYY年MM月DD日')} 至今`;
    } else if (dateRange[1]) {
      dateRangeText += `至 ${dateRange[1].format('YYYY年MM月DD日')}`;
    } else {
      dateRangeText += '全部时间';
    }

    setStatistics({
      totalShifts: total,
      adjustedShifts: adjusted,
      cancelledShifts: cancelled,
      replacedShifts: replaced,
      adjustedChange,
      cancelledChange,
      filterDateRange: dateRangeText
    });
  };

  // 快速筛选
  const handleQuickFilter = (range) => {
    let start = null;
    let end = dayjs();

    switch (range) {
      case '7':
        start = dayjs().subtract(7, 'day');
        break;
      case '30':
        start = dayjs().subtract(30, 'day');
        break;
      case 'month':
        start = dayjs().startOf('month');
        break;
      case 'lastmonth':
        start = dayjs().subtract(1, 'month').startOf('month');
        end = dayjs().subtract(1, 'month').endOf('month');
        break;
      case 'quarter':
        const currentQuarter = Math.floor(dayjs().month() / 3);
        start = dayjs().month(currentQuarter * 3).startOf('month');
        break;
    }

    setDateRange([start, end]);
  };

  // 重置筛选条件
  const resetFilters = () => {
    setDateRange([dayjs().subtract(45, 'day'), dayjs()]);
    setDoctorFilter('');
    setStatusFilter('');
  };

  // 查看排班详情
  const viewScheduleDetail = (record) => {
    setSelectedSchedule(record);
    setDetailModalVisible(true);
    // 重置详情页标签为默认
    setActiveDetailTab('reservations');
  };



 
  // 表格列定义
  const columns = [
    {
      title: '排班日期',
      dataIndex: 'date',
      key: 'date',
      render: (date) => dayjs(date).format('YYYY-MM-DD')
    },
    {
      title: '时间段',
      dataIndex: 'timeSlot',
      key: 'timeSlot'
    },
    {
      title: '原排班员工',
      dataIndex: 'originalDoctor',
      key: 'originalDoctor',
      render: (doctor, record) => (
        <div className="flex items-center">
          <Avatar src={doctor.avatar} alt={doctor.name} className={record.status === 'canceled' ? 'opacity-70' : ''} />
          <span className={`ml-2 ${record.status === 'canceled' ? 'text-gray-500 line-through' : ''}`}>
            {doctor.name}
           
          </span>
        </div>
      )
    },
    {
      title: '实际排班员工',
      dataIndex: 'actualDoctor',
      key: 'actualDoctor',
      render: (doctor, record) => {
        if (!doctor) {
          return <span className="text-gray-500">-（未补排）</span>;
        }

        return (
          <div className="flex items-center">
            <Avatar src={doctor.avatar} alt={doctor.name} />
            <span className="ml-2">
              {doctor.name}

            </span>
          </div>
        );
      }
    },
    {
      title: '服务项目',
      dataIndex: 'service',
      key: 'service',
      render: (service, record) => (
        <span className={record.status === 'canceled' ? 'text-gray-500 line-through' : ''}>
          {service}
        </span>
      )
    },
    {
      title: '排班状态',
      dataIndex: 'status',
      key: 'status',
      render: (status) => getStatusBadge(status)
    },
    {
      title: '操作人',
      dataIndex: 'operator',
      key: 'operator'
    },
    {
      title: '操作',
      key: 'action',
      render: (_, record) => (
        <Button
          type="primary"
          size="small"
          onClick={() => viewScheduleDetail(record)}
         
        >
          查看详情
        </Button>
      )
    }
  ];

  // 分页变化处理
  const handleTableChange = (pagination) => {
    setCurrentPage(pagination.current);
    setPageSize(pagination.pageSize);
  };

  return (
    <div>
      {isShow ? (
        <Skeleton paragraph={{ rows: 10 }} active></Skeleton>
      ) : (
        <div>
          <div>
            {/* 页面标题和操作区 */}
            <div style={{display:"flex",justifyContent:"space-between"}}>
             
                <div>
                  <h1 className="text-2xl md:text-3xl font-bold text-gray-700">排班历史</h1>
                  <p className="text-gray-500 mt-1">查询、查看历史排班记录与统计数据</p>
                </div>
                <div style={{marginTop:20}}>
                 
                  {/* <Button
                    icon={<BarChartOutlined />}
                    onClick={() => setStatsModalVisible(true)}
                    style={{ backgroundColor: '#8B5A2B', borderColor: '#8B5A2B', color: 'white' }}
                  >
                    历史统计
                  </Button> */}
                </div>
             
            </div>

            {/* 高级筛选区 */}
            <Card>
              <div style={{display:"flex"}}>
                <FilterOutlined style={{ color: '#8B5A2B', marginRight: 8,fontSize:20 }} />
                <h3 style={{marginTop:8,fontWeight:"bold"}}>高级筛选</h3>
              </div>

              <div style={{display:"flex",gap:10}}>
                {/* 时间范围筛选 */}
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">时间范围</label>
                  <DatePicker.RangePicker
                    value={dateRange}
                    onChange={(dates) => setDateRange(dates)}
                    style={{ width: '100%' }}
                  />
                </div>

                {/* 员工筛选 */}
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">选择员工</label>
                  <Select
                    value={doctorFilter}
                    onChange={setDoctorFilter}
                    placeholder="全部员工"
                    style={{ width: '100%' }}
                  >
                    <Select.Option value="">全部员工</Select.Option>
                    {doctors.filter((v, i, a) => a.findIndex(d => d.id === v.id) === i).map(doctor => (
                      <Select.Option key={doctor.id} value={doctor.id}>
                        {doctor.name}（{doctor.specialty}）
                      </Select.Option>
                    ))}
                  </Select>
                </div>

                {/* 排班状态筛选 */}
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">排班状态</label>
                  <Select
                    value={statusFilter}
                    onChange={setStatusFilter}
                    placeholder="全部状态"
                    style={{ width: '100%' }}
                  >
                    <Select.Option value="">全部状态</Select.Option>
                    <Select.Option value="normal">正常排班</Select.Option>
                    <Select.Option value="adjusted">已调班</Select.Option>
                    <Select.Option value="canceled">已取消</Select.Option>
                    <Select.Option value="replaced">代班</Select.Option>
                  </Select>
                </div>

                {/* 操作按钮 */}
                <div style={{marginTop:20}}>
                  <Button
                    onClick={() => {}}
                    style={{ backgroundColor: '#8B5A2B', borderColor: '#8B5A2B', color: 'white' }}
                  >
                    筛选
                  </Button>
                  <Button
                    onClick={resetFilters}
                    style={{ borderColor: '#d9d9d9', color: '#333',marginLeft:10 }}
                  >
                    重置
                  </Button>
                </div>
              </div>

              {/* 快速筛选标签 */}
              <div style={{marginTop:10}}>
                {[
                  { range: '7', label: '近7天' },
                  { range: '30', label: '近30天' },
                  { range: 'month', label: '本月' },
                  { range: 'lastmonth', label: '上月' },
                  { range: 'quarter', label: '本季度' }
                ].map(item => (
                  <Tag
                    key={item.range}
                    onClick={() => handleQuickFilter(item.range)}
                    style={{
                      cursor: 'pointer',
                      backgroundColor: dateRange[0] && dayjs().subtract(parseInt(item.range), 'day').isSame(dateRange[0], 'day')
                        ? 'rgba(139, 90, 43, 0.1)'
                        : '#f0f0f0',
                      color: dateRange[0] && dayjs().subtract(parseInt(item.range), 'day').isSame(dateRange[0], 'day')
                        ? '#8B5A2B'
                        : '#333'
                    }}
                  >
                    {item.label}
                  </Tag>
                ))}
              </div>
            </Card>

            {/* 统计卡片 */}
            <div style={{display:"flex",gap:10,marginTop:10,marginBlock:10}}>
              <Card style={{flex:1}} className="border-0 shadow-sm bg-white">
                <Statistic
                  title="总排班次数"
                  value={statistics.totalShifts}
                  prefix={<UserSwitchOutlined style={{ color: '#8B5A2B' }} />}
                  valueStyle={{ color: '#333' }}
                />
              </Card>
              <Card style={{flex:1}} className="border-0 shadow-sm bg-white">
                <Statistic
                  title="调班次数"
                  value={statistics.adjustedShifts}
                  prefix={<UserSwitchOutlined style={{ color: '#faad14' }} />}
                  valueStyle={{ color: '#faad14' }}
                  changeRate={statistics.adjustedChange}
                  changeRateDirection={statistics.adjustedChange > 0 ? 'up' : 'down'}
                />
              </Card>
              <Card style={{flex:1}} className="border-0 shadow-sm bg-white">
                <Statistic
                  title="取消次数"
                  value={statistics.cancelledShifts}
                  prefix={<UserSwitchOutlined style={{ color: 'red' }} />}
                  valueStyle={{ color: 'red' }}
                  changeRate={statistics.cancelledChange}
                  changeRateDirection={statistics.cancelledChange > 0 ? 'up' : 'down'}
                />
              </Card>
              <Card style={{flex:1}} className="border-0 shadow-sm bg-white">
                <Statistic
                  title="代班次数"
                  value={statistics.replacedShifts}
                  prefix={<UserSwitchOutlined style={{ color: 'blue' }} />}
                  valueStyle={{ color: 'blue' }}
                />
              </Card>
            </div>

            {/* 排班历史表格 */}
            <Card className="border-0 shadow-sm">
              <Spin spinning={loading} tip="加载排班历史数据中...">
                <Table
                  columns={columns}
                  dataSource={filteredData.slice((currentPage - 1) * pageSize, currentPage * pageSize)}
                  rowKey="id"
                  pagination={{
                    current: currentPage,
                    pageSize: pageSize,
                    total: totalRecords,
                    showSizeChanger: true,
                    showTotal: (total) => `共 ${total} 条记录`,
                    pageSizeOptions: ['5', '10', '20', '50'],
                  }}
                  onChange={handleTableChange}
                  scroll={{ x: 'max-content' }}
                  className="bg-white"
                />
              </Spin>
            </Card>

            {/* 排班详情模态框 */}
            <Modal
              title={`排班详情 - ${selectedSchedule?.date || ''}`}
              open={detailModalVisible}
              onCancel={() => setDetailModalVisible(false)}
              width={800}
              style={{top:"50px"}}
              footer={[
                <Button key="close" onClick={() => setDetailModalVisible(false)}>
                  关闭
                </Button>
              ]}
            >
              {selectedSchedule && (
                <div>
                  <ArrangeDetails data={selectedSchedule}></ArrangeDetails>
                 
                </div>
                
              )}
            </Modal>

            {/* 统计数据模态框 */}
            <Modal
              title="排班历史统计"
              open={statsModalVisible}
              onCancel={() => setStatsModalVisible(false)}
              width={800}
              style={{top:"50px"}}
              footer={[
                <Button key="close" onClick={() => setStatsModalVisible(false)}>
                  关闭
                </Button>
              ]}
            >
              <div>

                <HistoryStatsModal></HistoryStatsModal>
              </div>
              
             
            </Modal>
          </div>
        </div>
      )}
    </div>
  );
}
    